package org.example.core;

import org.example.constant.constant;

import java.util.concurrent.atomic.LongAdder;

public class DownloaderInfoThread implements Runnable{

    /*
     展示下载信息
     */

    //下载文件总大小
    private long httpContentLength;

    //已下载文件大小
    public static LongAdder finishedSize =  new LongAdder();

    //本次累计下载大小
    public static volatile LongAdder downSize = new LongAdder();

    //上次累计下载大小
    public double preSize;

    public DownloaderInfoThread(long httpContentLength){
        this.httpContentLength = httpContentLength;
    }

    @Override
    public void run() {

        //文件总大小转换 字节-->mb
        String httpFileSize = String.format("%.2f",httpContentLength / constant.MB);

        //计算每秒下载速度  单位：kb
        int speed  = (int) ((downSize.doubleValue() - preSize) / 1024d);
        preSize  = downSize.doubleValue();

        //剩余文件大小
        double remainSize = httpContentLength - finishedSize.doubleValue() -downSize.doubleValue();

        //计算剩余时间
        String remainTime =String.format("%.1f",remainSize /1024d / speed);

        if ("Infinity".equalsIgnoreCase(remainTime)){
            remainTime = "--";
        }

        //已下载大小
        String currentFileSize = String.format("%.2f",(downSize.doubleValue() - finishedSize.doubleValue()) /  constant.MB);

        String downInfo = String.format("已下载  %smb/%smb,  速度%skb/s,    剩余时间%ss",
                currentFileSize,httpFileSize,speed,remainTime);


        System.out.print("\r");
        System.out.print(downInfo);
    }
}
